package com.ilove.weather;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;


public class DataAccess {

	public static String getData(String serverUrl) throws IOException {
		HttpConnection connection = null;
		InputStream inputstream = null;
		String str = null;
		int actual = 0;
		try {
			connection = (HttpConnection) Connector.open(serverUrl);
			// HTTP Request
			connection.setRequestMethod(HttpConnection.GET);
			// connection.setRequestProperty("Content-Type", "//text plain");
			connection.setRequestProperty("Connection", "close");
			// HTTP Response
			if (connection.getResponseCode() == HttpConnection.HTTP_OK) {
				inputstream = connection.openInputStream();
				int length = (int) connection.getLength();
				if (length != -1) {
					byte[] incomingData = new byte[length];
					// inputstream.read(incomingData);
					actual = inputstream.read(incomingData);
					str = new String(incomingData, 0, actual, "UTF-8");
				} else {
					ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
					int ch;
					while ((ch = inputstream.read()) != -1) {
						bytestream.write(ch);
					}
					str = new String(bytestream.toByteArray(), 0, bytestream
							.size(), "UTF-8");
					bytestream.close();
				}
			}
		} catch (IOException error) {
		} finally {
			if (inputstream != null) {
				try {
					inputstream.close();
				} catch (Exception error) {
					/* log error */
				}
			}
			if (connection != null) {
				try {
					connection.close();
				} catch (Exception error) {
					/* log error */
				}
			}
		}
		return str;
	}
}
